<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\goods\Order;
use app\common\controller\Api;
use app\common\controller\Payment;
use function EasyWeChat\Kernel\Support\get_client_ip;
use think\Controller;
use think\Db;
use think\Request;


class Withdraw extends Api
{
    private static $model;
//    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new \app\common\model\Withdraw();
    }

    /**
     * 提现记录
     * @return \think\Response
     */
    public function lists()
    {
        $pageSize = input('pagesize', 15);
        $userId = $this->auth->id;

        $where = [
            'user_id' => $userId,
        ];
        $lists = self::$model->where($where)->order('createtime desc')->paginate($pageSize);

        $this->success('提现记录', $lists);
    }

    /**
     * 余额提现
     */
    public function create()
    {
        $money = input('money');
        if (!$money || $money <= 0) {
            $this->error('必须输入正确提现金额！');
        }

        $userId = $this->auth->id;
        $user = \app\common\model\User::find($userId);
        if ($user->money < $money) {
            $this->error('余额不足！');
        }

        $type = input('type', 1);
        $orderNum = create_order($userId);

        $user->money -= $money;
        $odata = [
            'order_num' => $orderNum,
            'user_id' => $userId,
            'money' => $money,
            'hasmoney' => $user->money,
            'account' => '',
            'type' => $type,
            'status' => 'created',
        ];

        Db::startTrans();
        try {
            $user->save();
            $ret = \app\common\model\Withdraw::create($odata);
            // 余额流水
            $before = $user->money + $money;
            $orderNum = create_order($user->id);
            $mdata = [
                'order_num' => $orderNum,
                'user_id' => $user->id,
                'record_type' => 0,
                'money' => $money,
                'before' => $before,
                'after' => $user->money,
                'relation_type' => 4,// 提现
                'relation_id' => $ret->id,
                'memo' => '申请提现扣减' . $money . '余额',
            ];

            \app\common\model\UserMoneyLog::create($mdata);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error('提现申请失败！');
        }

        $this->success('提现申请成功，等待后台审核！');
    }
}
